package nz.ac.massey.pp.javamem.gc;

import java.util.ArrayList;
import java.util.List;

/**
 * Example showing the it is possible to keep on creating objects,
 * the JVM will automatically free memory via garbage collection. 
 * This example is slightly more complicated than CreateInfinitelyManyObjects2,
 * as the objects created are now referenced by a list, and the objects themselves 
 * also have a backreference to the list.  
 * However, the lists themselves are not referenced, so garbage collection
 * still works. This shows that GC works recursively, and can handle 
 * cyclic dependencies.
 * @author jens dietrich
 */

public class CreateInfinitelyManyObjects3 {

	public static void main(String[] args) throws Exception {
		
		while (true) {
			List list = new ArrayList();
		    for (int i=0;i<1000000;i++) {
		    	ObjectInList nextObject = new ObjectInList();
		    	nextObject.container = list;
		    	list.add(nextObject);
		    }
		    
		    // break between, allows JVM to clean up (GC !) 
		    Thread.sleep(100);
		}	
	}
}
